<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-row>
        <el-form-item label="渠道客户" prop="orderType">
          <el-select
            v-model="queryParams.orderType"
            placeholder="请选择渠道客户"
            clearable
            class="!w-120px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_ORDER_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门店" prop="storeId">
          <el-select
            v-model="queryParams.storeId"
            placeholder="请选择门店"
            clearable
            filterable
            class="!w-150px"
          >
            <el-option
              v-for="dict in storeList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车牌" prop="licensePlate">
          <el-input
            v-model="queryParams.licensePlate"
            placeholder="请输入车牌"
            clearable
            @keyup.enter="handleQuery"
            class="!w-120px"
          />
        </el-form-item>

        <el-form-item label="审核日期" prop="auditDate">
          <el-date-picker
            v-model="queryParams.auditDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-form-item>


        <!--        <el-form-item label="联系电话" prop="telephone">-->
        <!--          <el-input-->
        <!--            v-model="queryParams.telephone"-->
        <!--            placeholder="请输入联系电话"-->
        <!--            clearable-->
        <!--            @keyup.enter="handleQuery"-->
        <!--            class="!w-120px"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px"/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px"/>
            重置
          </el-button>
        </el-form-item>

      </el-row>

    </el-form>


    <el-row class="mt-15px">
      <el-col :span="6">
        <el-radio-group v-model="queryParams.payStatus" size="small">
          <el-radio-button @click="handlePayStatusQuery(undefined)" label="所有" value="undefined"/>
          <el-radio-button @click="handlePayStatusQuery(1)" label="未付款" value="1"/>
          <el-radio-button @click="handlePayStatusQuery(2)" label="付款中" value="2"/>
          <el-radio-button @click="handlePayStatusQuery(3)" label="已付款" value="3"/>
        </el-radio-group>
      </el-col>

      <el-col :span="6">
        <el-radio-group v-model="queryParams.checkStatus" size="small">
          <el-radio-button @click="handleCheckStatusQuery(undefined)" label="所有" value="undefined"/>
          <el-radio-button @click="handleCheckStatusQuery(1)" label="未对账" value="1"/>
          <el-radio-button @click="handleCheckStatusQuery(3)" label="已对账" value="3"/>
        </el-radio-group>
      </el-col>


      <el-col :span="6">
        <el-radio-group v-model="queryParams.auditStatus" size="small">
          <el-radio-button @click="handleAuditStatusQuery(undefined)" label="所有" value="undefined"/>
          <el-radio-button @click="handleAuditStatusQuery(2)" label="通过" value="2"/>
          <el-radio-button @click="handleAuditStatusQuery(1)" label="驳回" value="1"/>
          <el-radio-button @click="handleAuditStatusQuery(3)" label="未审核" value="3"/>
        </el-radio-group>
      </el-col>
    </el-row>

    <el-switch inactive-value="0" active-value="1" v-model="showBatchPayment"/>

    <el-row v-if="showBatchPayment==1" class="mt-20px">
      <el-button @click="handleBatchPayment" type="primary">批量付款申请</el-button>
    </el-row>

  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table ref="multipleTableRef" @selection-change="handleSelectionChange"
              :span-method="objectSpanMethod" v-loading="loading"
              :summary-method="getSummaries" show-summary
              border :data="list" :stripe="true" :show-overflow-tooltip="true">

      <el-table-column fixed="left" type="selection" width="40"/>

      <el-table-column fixed="left" class="edit-div" label="操作" min-width="60" align="center">
        <template #default="scope">
          <el-popover :visible="popoverVisible == scope.row.id" placement="bottom-start"
                      :width="100">

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handlePic(scope.row)"
                >
                  查看/审核
                </el-button>
              </el-col>
            </el-row>
            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handleCmmPic(scope.row)"
                >
                  提交平台审核
                </el-button>
              </el-col>
            </el-row>


            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  style="margin:0"
                  type="primary"
                  @click="handlePay(scope.row)"
                >
                  付款申请
                </el-button>
              </el-col>
            </el-row>


            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  style="margin:0"
                  type="primary"
                  @click="lookPayment(scope.row)"
                >
                  查看付款单
                </el-button>
              </el-col>
            </el-row>

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  style="margin:0"
                  type="primary"
                  @click="lookReceipt(scope.row)"
                >
                  查看收款单
                </el-button>
              </el-col>
            </el-row>

            <div class="popoverCloseBtn" @click="closePopover()">关闭</div>
            <template #reference>
              <img class="linkBtn" src="@/assets/imgs/more_edit.png"
                   @contextmenu.prevent="handleRightClick(scope.row.id)"
                   @click="handlePic(scope.row)"/>
            </template>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column
        label="日期"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="120px"
      />
      <!--      <el-table-column label="编号" align="center" prop="id"/>-->
      <el-table-column label="门店" min-width="200" prop="storeId">
        <!--        <template #default="scope">-->
        <!--          <el-tag type="primary">{{ getStoreName(scope.row) }}</el-tag>-->
        <!--        </template>-->
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.storeName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="车牌" min-width="100" prop="licensePlate"/>
      <el-table-column label="车型" min-width="200" prop="carType"/>
      <el-table-column label="产品名称" min-width="200" prop="productName">
        <template #default="scope">
          <span class="productName" v-if="scope.row.productName !=null">
              <span type="primary" @click="getProductInfo(scope.row)">{{
                  scope.row.productName
                }}</span>
          </span>
        </template>
      </el-table-column>

      <el-table-column label="订单价格" align="center" min-width="130" prop="orderPrice">
        <template #default="scope">
          <el-input class="text-center-input" style="width: 60px"
                    @change="handleChangeOrderPrice(scope.row)" v-model="scope.row.orderPrice"/>
          <!--          <el-button type="primary" text size="small" @click="handleUpdateOrderPrice(scope.row)">-->
          <!--            修改-->
          <!--          </el-button>-->
        </template>

      </el-table-column>
      <el-table-column label="参考订单价" prop="historyPrice" width="120">
        <template #default="scope">
          <el-button
            link
            v-for="(value, index) in scope.row.orderPriceList" :key="index"
            type="primary"
            @click="openHistoryPriceDetail(scope.row,'channel')"
          >
            <el-tag type="success">
              {{ value }}
            </el-tag>
            <!--            <el-tag-->
            <!--              v-if="scope.row.historyOrderPrice != null && scope.row.historyOrderPrice.length > 0"-->
            <!--              type="success">{{-->
            <!--                scope.row.historyOrderPrice-->
            <!--              }}-->
            <!--            </el-tag>-->
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="派单价格" align="center" min-width="120" prop="dispatchPrice">
        <template #default="scope">
          <el-input class="text-center-input" style="width: 60px;text-align: center"
                    @change="handleChangeDispatchPrice(scope.row)"
                    v-model="scope.row.dispatchPrice"/>
          <!--          <el-button type="primary" text size="small" @click="handleUpdateDispatchPrice(scope.row)">-->
          <!--            修改-->
          <!--          </el-button>-->
        </template>
      </el-table-column>

      <el-table-column label="参考派单价" prop="historyPrice" width="120">
        <template #default="scope">
          <el-button
            link
            v-for="(value, index) in scope.row.dispatchPriceList" :key="index"
            type="primary"
            @click="openHistoryPriceDetail(scope.row,'dispatch')"
          >
            <el-tag type="success">
              {{ value }}
            </el-tag>
            <!--            <el-tag-->
            <!--              v-if="scope.row.historyDispatchPrice != null && scope.row.historyDispatchPrice.length > 0"-->
            <!--              type="success">{{-->
            <!--                scope.row.historyDispatchPrice-->
            <!--              }}-->
            <!--            </el-tag>-->
          </el-button>
        </template>
      </el-table-column>

      <el-table-column
        label="图片上传状态"
        align="center"
        prop="imgDate"
        :formatter="dateFormatter"
        width="120px"
      >
        <template #default="scope">
          <el-tag type="warning" v-if="scope.row.auditImgUrl == undefined">未上传</el-tag>
          <el-tag type="success" v-else>已上传</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图片审核" min-width="100" align="center" prop="auditStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_AUDIT_STATUS" :value="scope.row.auditStatus"/>
          <!--          <el-select v-model="scope.row.auditStatus">-->
          <!--            <el-option-->
          <!--              v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_AUDIT_STATUS)"-->
          <!--              :key="dict.value"-->
          <!--              :label="dict.label"-->
          <!--              :value="dict.value"-->
          <!--            />-->
          <!--          </el-select>-->
        </template>
      </el-table-column>
      <el-table-column
        label="审核日期"
        align="center"
        prop="auditDate"
        :formatter="dateFormatter2"
        width="120px"
      >
        <template #default="scope">
          <el-button
            type="text"
            @click="openPicAuditDate(scope.row)"
          >
            {{ formatDate(scope.row.auditDate, 'YYYY-MM-DD') }}
          </el-button>
        </template>

      </el-table-column>
      <el-table-column
        label="平台审核"
        align="center"
        prop="cmmAuditStatus"
        width="120px"
        fixed="left"
      >
        <template #default="scope">
          <div v-if="scope.row.cmmPartnerOrderNo != null">
            <el-tag type="warning" v-if="scope.row.cmmAuditStatus == null">未审核</el-tag>
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.cmmAuditDesc"
              placement="top-end"
            >
              <el-tag type="danger" v-if="scope.row.cmmAuditStatus == 3">驳回</el-tag>
            </el-tooltip>
            <el-tag type="success" v-if="scope.row.cmmAuditStatus == 2">通过</el-tag>
            <el-tag type="danger" v-if="scope.row.cmmAuditStatus == 1">取消订单</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="平台审核日期"
        align="center"
        prop="cmmAuditDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="对账状态" min-width="100" align="center" prop="checkStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_CHECK_STATUS" :value="scope.row.checkStatus"/>
          <!--          <el-select v-model="scope.row.checkStatus">-->
          <!--            <el-option-->
          <!--              v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_CHECK_STATUS)"-->
          <!--              :key="dict.value"-->
          <!--              :label="dict.label"-->
          <!--              :value="dict.value"-->
          <!--            />-->
          <!--          </el-select>-->
        </template>
      </el-table-column>
      <el-table-column
        label="对账日期"
        align="center"
        prop="checkDate"
        :formatter="dateFormatter"
        width="100px"
      />
      <el-table-column label="收款状态" align="center" min-width="90" prop="receiptStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_RECEIPT_STATUS" :value="scope.row.receiptStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="付款状态" align="center" min-width="90" prop="payStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_PAY_STATUS" :value="scope.row.payStatus"/>
        </template>
      </el-table-column>
      <el-table-column
        label="付款日期"
        align="center"
        prop="payDate"
        :formatter="dateFormatter"
        width="100px"
      />
      <el-table-column label="开启状态" align="center" min-width="100" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" min-width="100" prop="brandId">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_GLASS_BRAND" :value="scope.row.brandId"/>
        </template>
      </el-table-column>
      <el-table-column label="部位" min-width="100" prop="saleType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_SALE_TYPE" :value="scope.row.saleType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户" min-width="100" prop="customerName"/>
      <el-table-column label="单号" min-width="200" prop="no"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <!--      <el-table-column label="操作" min-width="180" align="center" fixed="right">-->
      <!--        <template #default="scope">-->

      <!--          <el-button-->
      <!--            link-->
      <!--            type="primary"-->
      <!--            @click="handlePic(scope.row)"-->
      <!--          >-->
      <!--            查看/提交-->
      <!--          </el-button>-->

      <!--          <el-button-->
      <!--            link-->
      <!--            type="primary"-->
      <!--            @click="handlePay(scope.row)"-->
      <!--          >-->
      <!--            付款申请-->
      <!--          </el-button>-->


      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>


  <Dialog title="审核图片详情" v-model="picDialogVisible" width="50%">
    <el-form v-loading="formLoading">
      <el-form-item label="" label-width="80px">
        <UploadImgs disabled v-model="picData.imgUrl"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="auditPic(2)" type="primary" :disabled="formLoading">通 过</el-button>
      <el-button @click="auditPic(1)">驳 回</el-button>
    </template>
  </Dialog>


  <Dialog title="审核图片详情" v-model="cmmPicDialogVisible" width="30%">
    <el-form v-loading="formLoading">

      <el-form-item v-for="item in checkItemList" :key="item.GoodsItemRuleID"
                    :label="item.CheckItemName" label-width="120px">
        <!--          仅能查看 disabled  可上传车妈妈审核图片-->
        <el-input v-if="item.MinImgNum ==0" disabled type="text" v-model="item.BusinessSuggestion"/>
        <UploadImgs v-else v-model="item.ImgUrls"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitCmm()" type="primary" :disabled="formLoading">上传平台</el-button>
    </template>
  </Dialog>

  <Dialog title="修改产品信息" v-model="productNameDialogVisible" width="28%">
    <el-form class="productNameForm" v-loading="formLoading">
      <el-form-item label="产品名称" label-width="80px">
        <el-input type="text" v-model="updateProdcutData.name"/>
      </el-form-item>
      <el-form-item label="工厂编号" label-width="80px">
        <el-input type="text" v-model="updateProdcutData.factoryNumber"/>
      </el-form-item>
      <el-form-item label="图片信息" label-width="80px">
        <UploadImgs limit="1" v-model="updateProdcutData.imgUrl"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateProductName" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="productNameDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!--  历史价格详情-->
  <el-dialog
    v-model="historyPriceDetailVisible"
    title="参考派单报价"
    width="40%"
  >
    <!--    <div style="text-align: center;margin-bottom: 20px">{{ historyPriceProductName }}</div>-->
    <!--    <el-tag class="mr-3" type="success">最低报价{{ historyPriceDetail.minDispatchPrice }}</el-tag>-->
    <!--    <el-tag class="mr-3" type="danger">最高报价{{ historyPriceDetail.maxDispatchPrice }}</el-tag>-->
    <el-tag class="mr-3" v-for="(value, key, index) in historyPriceDetail.mapDispatchPrice"
            :key="index">【{{ key }}】{{ value }}
    </el-tag>
    <el-table v-loading="historyPriceLoading" :data="historyPriceDetail.list" border :stripe="true"
              :show-overflow-tooltip="true">
      <el-table-column label="门店" align="center" prop="storeName"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="时间" align="center" prop="createTime" :formatter="dateFormatter2"/>
      <el-table-column label="派单价格" align="center" prop="dispatchPrice"/>
    </el-table>

  </el-dialog>


  <el-dialog
    v-model="historyChannelPriceDetailVisible"
    title="参考订单价格"
    width="40%"
  >
    <!--    <div style="text-align: center;margin-bottom: 20px">{{ historyPriceProductName }}</div>-->
    <!--    <el-tag class="mr-3" type="success">最低报价{{ historyPriceDetail.minOrderPrice }}</el-tag>-->
    <!--    <el-tag class="mr-3" type="danger">最高报价{{ historyPriceDetail.maxOrderPrice }}</el-tag>-->
    <el-tag class="mr-3" v-for="(value, key, index) in historyPriceDetail.mapPrice" :key="index">
      【{{ key }}】{{ value }}
    </el-tag>
    <el-table v-loading="historyPriceLoading" :data="historyPriceDetail.list" border :stripe="true"
              :show-overflow-tooltip="true">
      <el-table-column label="渠道" align="center" prop="orderType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_ORDER_TYPE" :value="scope.row.orderType"/>
        </template>
      </el-table-column>
      <el-table-column label="门店" align="center" prop="storeName"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="时间" align="center" prop="createTime" :formatter="dateFormatter2"/>
      <el-table-column label="渠道价格" align="center" prop="orderPrice"/>
    </el-table>

  </el-dialog>

  <!--  修改图片审核日期-->
  <el-dialog
    v-model="dialogPicDateVisible"
    title="修改图片审核日期"
    width="20%"
  >
    <el-date-picker
      v-model="picDateData.auditDate"
      type="date"
      placeholder="请选择日期"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogPicDateVisible = false">取消</el-button>
        <el-button type="primary" @click="dealPicAuditDate"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>


  <!-- 表单弹窗：添加/修改 -->
  <OrderForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import download from '@/utils/download'
import {OrderApi, OrderVO} from '@/api/dispatch/order'
import {StoreApi, StoreVO} from '@/api/dispatch/store'
import OrderForm from './OrderForm.vue'
import ContentWrap from "@/components/ContentWrap/src/ContentWrap.vue";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import {stopPropagation} from "diagram-js/lib/util/Event";
import {ProductApi} from "@/api/erp/product/product";
import {InquiryOrderApi} from "@/api/erp/inquiryorder";
import {string} from "vue-types";
import {getCmmOrderCheckItemValue, postOrderCheckItem} from "@/api/system/cmm";
import {erpPriceInputFormatter, getSumValue} from "@/utils";
import {PaymentApi} from "@/api/dispatch/payment";
import {ReceiptApi} from "@/api/dispatch/receipt";

import {dateFormatter2, dateFormatter, formatDate} from '@/utils/formatTime'

const checkItemList = ref([]) // 车妈妈检查项

/** 派单系统 订单 列表 */
defineOptions({name: 'Order'})

const message = useMessage() // 消息弹窗


const showBatchPayment = ref(0)

const cmmPicDialogVisible = ref(false) // 车妈妈图片上传

const historyPriceLoading = ref(true) // 列表的加载中
const historyPriceDetailVisible = ref(false) // 历史价格详情

const historyPriceList = ref([]) // 历史价格详情

const historyPriceProductName = ref()

const historyChannelPriceDetailVisible = ref(false) // 历史价格详情


const dialogPicDateVisible = ref(false)

const picDateData = reactive({
  id: undefined,
  auditDate: undefined
})

const historyPriceDetail = reactive({
  list: [],
  mapPrice: undefined,
  mapDispatchPrice: undefined,

  minDispatchPrice: 0,
  maxDispatchPrice: 0,
  minOrderPrice: 0,
  maxOrderPrice: 0
})

const getSummaries = (param) => {
  const {columns, data} = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {
    if (['orderPrice'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumOrderPrice.value);
    } else if (['dispatchPrice'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumDispatchPrice.value);
    } else {
      sums[index] = ''
    }
  })

  return sums
}

const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}


const popoverVisible = ref();


const cmmPartnerOrderNo = ref()
const cmmOrderPrice = ref()

const {t} = useI18n() // 国际化
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const loading = ref(true) // 列表的加载中
const productNameDialogVisible = ref(false)
const dispatchDialogVisible = ref(false)
const picDialogVisible = ref(false)
const list = ref<OrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderType: undefined,
  licensePlate: undefined,
  auditDate: [],
  storeId: undefined,
  // dispatchType: 1,//派单状态(合作门店)
  telephone: undefined,
  customerName: undefined,
  auditStatus: undefined,
  checkStatus: undefined,
  payStatus: undefined
})
const updateProdcutData = reactive({
  id: undefined,
  name: undefined,
  factoryNumber: undefined,
  imgUrl: undefined
})


/**
 * 支付状态检索
 */
const handlePayStatusQuery = (status) => {
  queryParams.payStatus = status;
  getList()
}

/**
 * 对账状态检索
 */
const handleCheckStatusQuery = (status) => {
  queryParams.checkStatus = status;
  getList()
}


/**
 * 图片审核状态检索
 */
const handleAuditStatusQuery = (status) => {
  queryParams.auditStatus = status;
  getList()
}

const openPopoverVisible = async (id) => {
  // if (popoverVisible.value == null) {
  popoverVisible.value = id;
  // } else {
  //   popoverVisible.value = null;
  // }
}

const closePopover = async () => {
  popoverVisible.value = null;
}
const handleRightClick = (id) => {
  popoverVisible.value = id;
};

const objectSpanMethod = (param) => {
  // // 如果是第一列，则合并所有行
  // if (param.rowIndex === 0 && param.columnIndex === 0) {
  //   return {
  //     rowspan: 10,
  //     colspan: 1,
  //   };
  // }
  // // 非第一列，不合并
  // return {
  //   rowspan: 1,
  //   colspan: 1,
  // };

}

/**
 * 批量付款
 */
const handleBatchPayment = async () => {

  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要付款的订单');
    return;
  }

  let loading;
  ElMessageBox.confirm('确定批量付款吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    loading = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    await OrderApi.batchCreatePaymentOrder(multipleSelection.value);
    ElMessage.success('处理成功');
  }).finally(() => {
    multipleTableRef.value!.clearSelection()
    getList();
    loading.close();
  })
}

/**
 * 修改图片日期
 */
const dealPicAuditDate = async () => {

  //是否修改
  if (picDateData.auditDate == null) {
    return ElMessage.error('请选择日期');
  }

  if (picDateData.auditDate > new Date().getTime()) {
    ElMessage.error('审核日期不能大于今天')
    return
  }

  await message.confirm('确定要修改图片审核日期吗?');

  picDateData.auditDate = new Date(picDateData.auditDate).getTime();
  try {
    await OrderApi.dealPicAuditDate(picDateData);

    ElMessage.success('修改成功');

  } finally {
    getList();
    dialogPicDateVisible.value = false;
  }

}

const openPicAuditDate = async (row) => {
  picDateData.id = row.id;
  picDateData.auditDate = row.auditDate;
  dialogPicDateVisible.value = true;
}


/**
 * 查看付款单
 * @param row
 */
const lookPayment = async (row) => {
  let data = await PaymentApi.getByDispatchOrderId(row.id);

  if (data == null) {
    return ElMessage.error('该订单未生成付款单');
  }

  let paymentId = data.id;
  let ids = [paymentId];

  push({
    path: "/dispatch/finance/payment/payment",
    query: {doType: "query", data: ids}
  });
}

/**
 * 查看收款
 * @param row
 */
const lookReceipt = async (row) => {
  let data = await ReceiptApi.getByDispatchOrderId(row.id);

  if (data == null) {
    return ElMessage.error('该订单未生成收款单');
  }

  let receiptId = data.id;
  let ids = [receiptId];

  push({
    path: "/dispatch/finance/receipt/receipt",
    query: {doType: "query", data: ids}
  });
}


/**
 * 处理店铺名称
 * @param id
 */
const getStoreName = (row) => {
  let id = row.storeId;
  const store = storeList.value.find(item => item.id === id);

  if (row.dispatchType === 2) {
    return '自营门店'
  }

  let belongProvince = store.belongProvince != null ? store.belongProvince + ' ' : '';
  let belongCity = store.belongCity != null ? store.belongCity + ' ' : '';
  let belongDistrict = store.belongDistrict != null ? store.belongDistrict + ' ' : '';
  return belongProvince + belongCity + belongDistrict + store.name;
}

/**
 * 派单相关数据
 */
const dispatchData = reactive({
  id: undefined,
  orderType: 2,
  storeId: undefined
})

const payData = reactive({
  id: undefined,
  payMode: undefined //付款方式
})

//查看价格详情
const openHistoryPriceDetail = async (row, type: string) => {

  historyPriceProductName.value = row.productName;
  let productId = row.productId;
  if (type === 'channel') {
    historyChannelPriceDetailVisible.value = true;
  } else {
    historyPriceDetailVisible.value = true;
  }
  historyPriceLoading.value = true;
  historyPriceList.value = [];

  // let r = await InquiryOrderApi.historyPriceDetail(productId)
  let r = await OrderApi.selectHistoryPriceRecord(productId);


  historyPriceDetail.list = r.list;

  historyPriceDetail.mapPrice = r.mapPrice;
  historyPriceDetail.mapDispatchPrice = r.mapDispatchPrice;
  //
  // historyPriceDetail.minDispatchPrice = r.minDispatchPrice;
  // historyPriceDetail.maxDispatchPrice = r.maxDispatchPrice;
  // historyPriceDetail.minOrderPrice = r.minOrderPrice;
  // historyPriceDetail.maxOrderPrice = r.maxOrderPrice;

  historyPriceLoading.value = false;
}

const getProductInfo = async (row) => {
  //加载中
  productNameDialogVisible.value = true;
  formLoading.value = true;
  try {
    const res = await ProductApi.getProduct(row.productId);
    updateProdcutData.id = res.id;
    updateProdcutData.name = res.name;
    updateProdcutData.factoryNumber = res.factoryNumber;
    updateProdcutData.imgUrl = res.imgUrl;
  } finally {

    formLoading.value = false;
  }
}

//修改订单价格
const handleChangeOrderPrice = (row) => {

  ElMessageBox.confirm(
    '确定要修改订单价格吗?',
    '修改订单价格',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
    .then(async () => {

      await handleUpdateOrderPrice(row);

      ElMessage({
        type: 'success',
        message: '修改成功',
      })
      getList();
    })
    .catch(async () => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
      getList();
    })
}

//修改产品信息
const updateProductName = async () => {
  //修改中
  formLoading.value = true;
  try {
    await ProductApi.updateName(updateProdcutData)
    ElMessage({
      type: 'success',
      message: '修改成功',
    })
    productNameDialogVisible.value = false;
    formLoading.value = false;
    getList();
  } catch (e) {
  }
}

//修改派单价格
const handleChangeDispatchPrice = (row) => {

  ElMessageBox.confirm(
    '确定要修改派单价格吗?',
    '修改派单价格',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
    .then(async () => {

      await handleUpdateDispatchPrice(row);

      ElMessage({
        type: 'success',
        message: '修改成功',
      })
      getList();
    })
    .catch(async () => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
      getList();
    })
}
/**
 * 修改销售价
 */
const orderPriceData = reactive({
  id: undefined,
  orderPrice: 0
})
const handleUpdateOrderPrice = async (row) => {
  orderPriceData.id = row.id;
  orderPriceData.orderPrice = row.orderPrice;

  if (!isPositiveInteger(orderPriceData.orderPrice)) {
    message.error('销售价必须为正整数')
    getList()
    return
  }

  try {
    await OrderApi.updateOrderPrice(orderPriceData)
    message.success(t('修改成功'))
    getList()
  } catch (e) {
    console.error(e)
  }
}

function isPositiveInteger(str) {
  // 正则表达式匹配正整数，包括没有前导零的整数
  const pattern = /^[1-9]\d*$/;
  return pattern.test(str);
}

/**
 * 修改派单价
 */
const dispatchPriceData = reactive({
  id: undefined,
  dispatchPrice: 0
})
const handleUpdateDispatchPrice = async (row) => {
  dispatchPriceData.id = row.id;
  dispatchPriceData.dispatchPrice = row.dispatchPrice;

  if (!isPositiveInteger(dispatchPriceData.dispatchPrice)) {
    message.error('派单价必须为正整数')
    getList()
    return
  }

  try {
    await OrderApi.updateDispatchPrice(dispatchPriceData)
    message.success(t('修改成功'))
    getList()
  } catch (e) {
    console.error(e)
  }
}


/**
 * 照片信息
 */
const picData = reactive({
  id: undefined,
  imgUrl: []
})
/**
 * 审核信息
 */
const auditData = reactive({
  id: undefined,
  auditStatus: undefined
})

const auditPic = async (auditStatus) => {
  auditData.auditStatus = auditStatus;
  try {
    await OrderApi.handleAuditStatus(auditData)
    message.success(t('处理成功'))
    picDialogVisible.value = false
    getList()
  } finally {
    picDialogVisible.value = false
  }
}

/**
 * 对账信息
 */
const checkData = reactive({
  id: undefined,
  checkStatus: undefined
})

const storeList = ref<StoreVO[]>([])
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const dialogVisible = ref(false);

const sumDispatchPrice = ref(0);
const sumOrderPrice = ref(0);
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderTailPage(queryParams)

    let page = data.page;
    list.value = page.list;
    total.value = page.total;

    let statistics = data.statistics;
    sumDispatchPrice.value = statistics.sumDispatchPrice;
    sumOrderPrice.value = statistics.sumOrderPrice;
  } finally {
    loading.value = false
  }
}


const handlePic = async (row) => {

  // if (row.auditImgUrl === undefined || row.auditImgUrl === null) {
  //   message.error("暂未上传图片");
  //   return;
  // }
  auditData.id = row.id;
  picDialogVisible.value = true;
  picData.id = row.id;
  picData.imgUrl = row.auditImgUrl;
  console.log(picData.imgUrl)
  popoverVisible.value = null;
}

const handleCmmPic = async (row) => {

  if (row.cmmPartnerOrderNo === null || row.cmmPartnerOrderNo === "") {
    message.error("非车妈妈订单");
    return;
  }

  cmmPartnerOrderNo.value = row.cmmPartnerOrderNo;

  let checkItem = await getCmmOrderCheckItemValue(cmmPartnerOrderNo.value);

  checkItemList.value = checkItem.Result;

  console.log(checkItemList.value)

  //checkItemList.value 不能大于4个（24/9/4增加了 车牌号）
  if (checkItemList.value.length > 4) {
    message.error("多订单项请手动处理");
    return;
  }

  await checkItemList.value.forEach(item => {
    if (item.MinImgNum == 0) {
      item.BusinessSuggestion = row.orderPrice;
    }
  });

  cmmPicDialogVisible.value = true;

}

//提交车妈妈资料
const submitCmm = async () => {

  //提交loading
  let loadingInstance = ElLoading.service({
    lock: true,
    text: '提交中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {


    const checkItemListCopy = JSON.parse(JSON.stringify(checkItemList.value));

    await checkItemListCopy.forEach(item => {
      if (item.ImgUrls.length > 0) {
        item.ImgUrls = item.ImgUrls.join(",");
      }
    });

    let orderNumber = cmmPartnerOrderNo.value;
    let cmmData = {
      orderNumber: orderNumber,
      checkItemDataList: checkItemListCopy
    }

    formLoading.value = true;

    await postOrderCheckItem(cmmData);

    //处理成功提示
    message.success(t("提交成功"))

    await getList()
    cmmPicDialogVisible.value = false;

  } catch {
  } finally {
    formLoading.value = false;
    loadingInstance.close();
  }
}


const handleDispatch = async (id: number) => {
  dispatchDialogVisible.value = true;

  dispatchData.id = id;
  dispatchData.sotreId = undefined;
  dispatchData.orderType = 2;//默认派单-渠道
}

/**
 * 提交派单
 */
const submitDispatch = async () => {
  formLoading.value = true;
  try {
    if (dispatchData.sotreId === undefined) {
      message.error("请选择门店");
      return;
    }

    await OrderApi.handleDispatch(dispatchData);
    message.success(t("处理成功"))
    await getList()
    dispatchDialogVisible.value = false;
  } catch {
  } finally {
    formLoading.value = false;
  }
}
const {push} = useRouter();

function openAddStore() {
  push("/dispatch/store?param=handAdd");
}

/**
 * 提交图片信息
 */
const submitPic = async () => {
  formLoading.value = true;
  try {
    await OrderApi.handlePic(picData);
    message.success(t("处理成功"))
    await getList()
    picDialogVisible.value = false;
  } catch {
  } finally {
    formLoading.value = false;
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  // queryParams.dispatchType = 1;

  getList()
}

/** 重置按钮操作 */
const resetQuery = async () => {
  await queryFormRef.value.resetFields()
  queryParams.dispatchType = 1;


  queryParams.payStatus = undefined;
  queryParams.auditStatus = undefined;
  queryParams.checkStatus = undefined;

  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

//付款申请
const handlePay = async (row) => {
  payData.id = row.id;

  payData.payMode = row.payMode;

  if (payData.payMode === 1) {//月结客服
    ElMessageBox.confirm(
      '月结客户，该订单是否现结？',
      '结算方式',
      {
        confirmButtonText: '现结',
        cancelButtonText: '月结',
        type: 'warning',
        center: true,
      }
    )
      .then(async () => {
        payData.payMode = 2;
      })
      .catch(() => {
      }).finally(async () => {
      await OrderApi.createPaymentOrder(payData);

      ElMessage({
        type: 'success',
        message: '创建成功',
      })
      getList();
    })
  } else {
    await OrderApi.createPaymentOrder(payData);

    ElMessage({
      type: 'success',
      message: '创建成功',
    })
  }


}


/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderApi.deleteOrder(id)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderApi.exportOrder(queryParams)
    download.excel(data, '派单系统 订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  storeList.value = await StoreApi.getStoreSimpleList();
  getList()
})

onActivated(async () => {
  popoverVisible.value = null;
  storeList.value = await StoreApi.getStoreSimpleList();
  getList()
})

</script>

<style lang="scss" scoped>
:deep(.el-input__inner) {
  //text-align: center !important;
}

.productName:hover {
  cursor: pointer;
}

//.productNameForm {
// }
</style>

